package com.example.java_chatroom.api;

import com.example.java_chatroom.model.User;
import com.example.java_chatroom.model.UserMapper;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 控制层
 * @author Q
 * @create 2025-07-02-20:14
 */
@RestController//返回结果以json/xml格式返回，无需在每个方法单独加上ControllerBody
public class UserAPI {
    @Resource//依赖注入，可以在非Spring框架中使用
    private UserMapper userMapper;

    /**
     * 登录接口
     * @param username
     * @param password
     * @param req
     * @return
     */
    @PostMapping("login")//RequestMapper的快捷方法，专门处理post请求
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req) {
        //1.判断用户是否存在,不存在返回错误信息，存在则判断密码，密码错误则返回错误信息
        User user = userMapper.selectByName(username);
        if(user == null || !user.getPassword().equals(password)) {
            System.out.println("账号/密码错误！" + user);
            return new User();//返回空
        }
        //2.用户+密码正确，创建会话(存储用户信息相当于是)
        HttpSession session = req.getSession(true);
//        不需要展示密码，将密码置为空
        user.setPassword("");
        //存储数据（会话）
        session.setAttribute("user",user);
        return user;//返回该对象
    }

    /**
     * 注册接口
     * @param username
     * @param password
     * @return
     */
    @PostMapping("register")
    @ResponseBody
    public Object register(String username,String password) {
        User user = null;
        try{
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            int ret = userMapper.insert(user);
            System.out.println("注册ret: " + ret);
            user.setPassword("");
        }catch (DuplicateKeyException e) {
            //如果抛出异常，则说明注册名重复，返回空即可
            user = new User();
            System.out.println("注册失败！username= " + username);
        }
        return user;
    }
    /**
     * 获取用户信息->确认是谁登录了聊天
     * @param req
     * @return
     */
    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req) {
        //1.从请求中，获取会话信息
        HttpSession session = req.getSession(false);//设置为false,不需要自动生成新session
        if(session == null) {
            System.out.println("[getUserInfo]获取不到session对象");
            return new User();//返回空user
        }
        //2.从会话中获取到用户对象信息
        User user = (User) session.getAttribute("user");
        if(user == null) {
            System.out.println("[getUserInfo]获取不到user对象");
            return new User();//返回空user
        }
        user.setPassword("");
        return user;
    }
}
